from PyQt5.QtWidgets import *
import sys
 
class QTextEditDemo(QWidget):
    def __init__(self):
        super(QTextEditDemo, self).__init__()
        self.initUI()
 
    def initUI(self):
        self.setWindowTitle('QTextEdit控件演示')
        self.resize(300,320)
 
        #定义控件
        self.textEdit=QTextEdit()
        self.buttonText=QPushButton('显示文本')
        self.buttonHTML=QPushButton('显示HTML')
        self.buttonToText = QPushButton('获取文本')
        self.buttonToHTML = QPushButton('获取HTML')
 
        #垂直布局
        layout=QVBoxLayout()
        layout.addWidget(self.textEdit)
        layout.addWidget(self.buttonText)
        layout.addWidget(self.buttonHTML)
        layout.addWidget(self.buttonToText)
        layout.addWidget(self.buttonToHTML)
 
        #绑定信号和槽
        self.buttonText.clicked.connect(self.onClick_buttonText)
        self.buttonHTML.clicked.connect(self.onClick_buttonHTML)
        self.buttonToText.clicked.connect(self.onClick_buttonToText)
        self.buttonToHTML.clicked.connect(self.onClick_buttonToHTML)
 
        self.setLayout(layout)
 
    #槽函数
    def onClick_buttonText(self):
        # 普通文本
        self.textEdit.setPlainText('Hello World!')
 
    def onClick_buttonHTML(self):
        #富文本（HTML）
        self.textEdit.setHtml('<font color="blue" size="5">Hello World</font>')
 
    def onClick_buttonToText(self):
        print(self.textEdit.toPlainText()) #控制台输出普通文本
 
    def onClick_buttonToHTML(self):
        print(self.textEdit.toHtml())#控制台输出HTML文本
 
 
if __name__=='__main__':
    app=QApplication(sys.argv)
    main=QTextEditDemo()
    main.show()
    sys.exit(app.exec_())
